<?php
namespace app\common\model\user;

use app\common\model\BaseModel;
use app\common\enum\user\balanceLog\BalanceLogSceneEnum;
use app\common\model\user\Sms as SmsModel;

/**
 * 用户信息认证
 */
class AttestationInfo extends BaseModel
{
    protected $pk = 'id';

    public function user()
    {
        return $this->hasOne(User::Class)->field('nickName');
    }

    public function add($data,$user)
    {
//        if(!$this->check($data)){
//            return false;
//        }
        $data['user_id'] = $user['user_id'];
        $check = $this->where(array('user_id'=>$user['user_id']))->find();
        unset($data['token']);
        if($check){
            unset($data['create_time']);
            if($check['types'] != $data['types']){
                $this->error = '不能同时认证两种类型';
                return false;
            }
            $data['update_time'] = time();
            $data['status'] = 0;
            $res = $this->where(array('id'=>$check['id']))->update($data);
        }else{
            $res = $this->save($data);
        }

        return $res;
    }

    public function get_details($user)
    {
        $info = $this->where(array('user_id'=>$user['user_id']))->find();

        return $info;
    }

    public function get_count()
    {
        return $this->alias('r')->join('jjjshop_user u','r.user_id=u.user_id','left')->where(array('r.status'=>0,'u.is_delete'=>0,'u.classify'=>2))->count();

    }

    /**
     * 验证
     */
    private function check($data)
    {

//        if( $data['code'] == 123456 ) {
//            return true;
//        }
        //判断验证码是否过期、是否正确
        $sms_model = new SmsModel();
        if($data['phone']){
            $mobile = $data['phone'];
        }
        if($data['phone']){
            $mobile = $data['person_phone'];
        }

        $sms_record_list = $sms_model
            ->where('mobile', '=', $mobile)
            ->order(['create_time' => 'desc'])
            ->limit(1)->select();

        if(count($sms_record_list) == 0){
            $this->error = '未查到短信发送记录';
            return false;
        }
        $sms_model = $sms_record_list[0];
        if((time() - strtotime($sms_model['create_time']))/60 > 30){
            $this->error = '短信验证码超时';
            return false;
        }
        if($sms_model['code'] != $data['code']){
            $this->error = '验证码不正确';
            return false;
        }
        return true;
    }

}